package com.example.demo2.action;

import com.example.demo2.bean.Cd;
import com.example.demo2.define.CDEvents;
import com.example.demo2.define.CDStates;
import com.example.demo2.define.Headers;
import com.example.demo2.define.Variables;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.action.Action;
import reactor.core.publisher.Mono;

import java.util.Map;

public class PlayingAction implements Action<CDStates, CDEvents> {

    @Override
    public void execute(StateContext<CDStates, CDEvents> context) {
        System.out.println("PlayingAction, execute 被执行");
        Map<Object, Object> variables = context.getExtendedState().getVariables();
        Object elapsed = variables.get(Variables.ELAPSEDTIME);
        Object cd = variables.get(Variables.CD);
        Object track = variables.get(Variables.TRACK);
        if (elapsed instanceof Long) {
            long e = ((Long)elapsed) + 1000l;
            if (e > ((Cd) cd).getTracks()[((Integer) track)].getLength()*1000) {
                context.getStateMachine()
                        .sendEvent(Mono.just(MessageBuilder
                                .withPayload(CDEvents.FORWARD)
                                .setHeader(Headers.TRACKSHIFT.toString(), 1).build()))
                        .subscribe();
            } else {
                variables.put(Variables.ELAPSEDTIME, e);
            }
        }
    }
}
